package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Component
public class CacheClient {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void set(String key, Object value, Long timeout, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), timeout, unit);
    }

    public void setWithLogicalExpire(String key, Object value, Long timeout, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(timeout)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData), timeout, unit);
    }

    public <R,ID> R queryWithPassThrough(
            String keyPrefix, ID id, Class<R> type, Function<ID, R> dbfallback, Long timeout, TimeUnit unit) {
        String key = keyPrefix + id;
        //先查redis cache
        String JSON = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(JSON)) {
            //存在，直接返回
            return JSONUtil.toBean(JSON, type);
        }
        //判断是否命中""空值
        if (JSON != null) {
            //命中""空值，直接返回
            return null;
        }
        //不存在，查数据库
        R r = dbfallback.apply(id);
        //不存在，返回错误
        if (r == null) {
            //不存在，写入redis cache
            stringRedisTemplate.opsForValue().set(key, "", timeout, unit);
            //返回错误
            return null;
        }
        //存在，写入redis cache
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(r), timeout, unit);
        //返回结果
        return r;
    }

    public <R,ID> R queryWithLogicalExpire(
            String keyPrefix, ID id, Class<R> type, Function<ID, R> dbfallback, Long timeout, TimeUnit unit) {
        String key = keyPrefix + id;
        //先查redis cache
        String JSON = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(JSON)) {
            //不存在，直接返回null
            return null;
        }
        //命中，存在
        //判断逻辑时间是否过期
        RedisData redisData = JSONUtil.toBean(JSON, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        if(redisData.getExpireTime().isAfter(LocalDateTime.now())){
            //未过期，返回商铺信息
            return r;
        }
        //过期，需要缓存重建
        //尝试获取锁
        //判断是否获取成功
        String lockKey = LOCK_SHOP_KEY + id;
        if (tryLock(lockKey)) {
            //获取成功
            //先再次查一下cache，判断是否过期，以免自己不是第一个获取到锁的线程，也就是说其他线程这时候已经更新好了数据
            String redisDataJson = stringRedisTemplate.opsForValue().get(key);
            RedisData bean = JSONUtil.toBean(redisDataJson, RedisData.class);
            R r1 = JSONUtil.toBean((JSONObject) bean.getData(), type);
            if(bean.getExpireTime().isAfter(LocalDateTime.now())){
                //没过期，说明拿到的是其他线程释放的锁，缓存已经重建好了，直接返回获取到的新数据就好
                return r1;
            }
            //如果过期，则自己是第一个，需要开启线程重建缓存，自己先返回旧数据
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //重建缓存
                    //查询数据库
                    R r2 = dbfallback.apply(id);
                    //封装数据
                    RedisData redisData1 = new RedisData();
                    redisData1.setData(r2);
                    redisData1.setExpireTime(LocalDateTime.now().plusSeconds(20));
                    //写入redis cache
                    stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData1), timeout, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }
        //返回旧数据
        return r;
    }

    //线程池,用于重建缓存
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);


    //获取锁
    public boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }


    //释放锁
    public void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

}
